package com.beamfield.common;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件解压缩
 */
public class CompressFileUtil {
    /**
     *  压缩文件
     * @param nameAndPathMap 压缩后的名称和需要压缩的文件路径
     * @param response
     * @param fileName 压缩包名称
     */
    public static void compressFiles(Map<String,String> nameAndPathMap, HttpServletResponse response, String fileName){
        byte[] buffer = new byte[1024];
        try {
            response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(fileName, "UTF-8")+".zip");
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            for(Map.Entry<String,String> entry : nameAndPathMap.entrySet()){
                FileInputStream fileInputStream = new FileInputStream(entry.getValue());
                out.putNextEntry(new ZipEntry(entry.getKey()));
                int len;
                while((len = fileInputStream.read(buffer)) > 0){
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fileInputStream.close();
            }
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
